
layui.use(['layer', 'form','element'], function(){
 /********************初始化******************/
  var layer = layui.layer
  ,form = layui.form
  ,element = layui.element;
  /********************初始化end******************/


 /********************渲染数据******************/
    function desktopInit(){
        //背景图
        var setbg=localStorage.getItem('setbg')
        if(setbg){
            $('.desktop-container').css('background-image',setbg)
        }
        //桌面
        var containerHeight=$('.desktop-container').height()
        var tplData={curData:navs,containerHeight:containerHeight}
        var html = template('tpl-desktopList', tplData);
        $('.desktop-main').html(html);
        //快速导航
        var localNavString=localStorage.getItem('localNav')
        var localNav=localNavString ? JSON.parse(localNavString) :{"total":0}
        var nowNavData={}
        $.each(localNav,function(k,v){
            if(k!="total"){
               var key=decodeURIComponent(k)
               nowNavData[key]=localNav[k]
            }
        })
        var sort_nowNavData=Object.keys(nowNavData).sort(function(x,y){return nowNavData[y]-nowNavData[x]})
        var localnum=nowNavData.length
        var localnav=sort_nowNavData
        var tplMenuData={curData:navs,localData:localnav,num:localnum}
        var htmlMenu = template('tpl-menuList', tplMenuData);
        $('.opening-menu-app-list').html(htmlMenu);
    }
    desktopInit()
    getNowTime()
    $(window).resize(function() { 
        desktopInit()
    })
 /********************渲染数据end******************/
    $(document).on('click','.desktop-app',function(){
            $(this).css('background','rgba(255,255,255,0.7)').siblings('.desktop-app').css('background','')
     })
    var tabarr={}
    $(document).on('dblclick','.desktop-app',openlayer)
    $('.opening-menu-app-list').on('click','.desktop-app',openlayer)
    $('.opening-menu').on('click','.desktop-app,.opening-menu-user-list a',function(){
        $('.opening-menu').removeClass('opening-menu-on')
    })
    element.on('tab(demo)', function(data){
        var tabid=$(this).attr('lay-id')
        var tab=tabarr[tabid]
        showtablayer(tabid,tab)
    });
    
    $('.taskbar-win.small-click').on('click',function(){
        var obj=$('.opening-menu')
        if(obj.hasClass('opening-menu-on')){
            obj.removeClass('opening-menu-on')
        }else{
             obj.addClass('opening-menu-on')
        }
        event.stopPropagation();
    })
     $(document).on('click',function(e){
         $('.opening-menu').removeClass('opening-menu-on')
     })
    $('.opening-menu').click(function (event){
        event.stopPropagation();//阻止事件向上冒泡
    });
    $('.taskbar-showdesktop').click(function (event){
        $.each(tabarr,function(k,v){
             layer.min(v)
        })
        $('.layui-tab-title li').each(function(k,v){
            $(v).removeClass('layui-this')
        })
    });
    
    /*******************自定义菜单*******************/
   //呼出菜单
    var myMenu = document.getElementById("myMenu");
    document.addEventListener("contextmenu", function(event){
        event.preventDefault();
        myMenu.style.display = "block";
        //获取鼠标视口位置
        myMenu.style.top = event.clientY + "px";
        myMenu.style.left = event.clientX + "px";
        
        //判断是否超出屏幕
        
        var mwidth= $(myMenu).width()
        var mheight= $(myMenu).height()
        if(mwidth+event.clientX>document.body.clientWidth){
             myMenu.style.left = (event.clientX-mwidth) + "px";
        }
        if(mheight+event.clientY>document.body.clientHeight){
             myMenu.style.top = (event.clientY-mheight) + "px";
        }
    });
    document.addEventListener("click", function(event){
        myMenu.style.display = "none";
    });
    //点击菜单栏目
    $('#myMenu ul li a').on('click',function(){
        var type=$(this).data('type')
        switch (type){
        	case 'launchFullscreen':
        	    launchFullscreen(document.documentElement)
        		break;
            case 'showdesktop':
                $.each(tabarr,function(k,v){
                     layer.min(v)
                })
                $('.layui-tab-title li').each(function(k,v){
                    $(v).removeClass('layui-this')
                })
                break;
            case 'closeall':
                layer.closeAll()
                break;
            case 'refresh':
                var iframediv=$('body').children('.layui-layer-iframe')
                var iframenames=[]
                iframediv.each(function(k,v){
                    iframenames.push($(v).children('.layui-layer-content').children('iframe').attr('id'))
                })
                $.each(iframenames,function(k,v){
                    document.getElementById(v).contentWindow.location.reload(true);
                })
                break;
            case 'loginout':
                sessionStorage.clear()
                setTimeout(function(){
                    window.location.href="login.html"
                },500)
                break;
            case 'technicalsupport':
                layer.alert('该系统由XXX提供技术支持，欢迎添加QQ:39275274。',{title:'技术支持'})
                break;
            case 'theme':
                setBackground()
                break;    
        	default:
        	    layer.alert('这个功能还没有实现哟')
        		break;
        }
    })
    /*******************自定义菜单end*******************/
   /*******************开始菜单*******************/
    $('.opening-menu-user-list a').on('click',function(){
        var type=$(this).data('type')
        switch (type){
            case 'launchFullscreen':
                launchFullscreen(document.documentElement)
                break;
            case 'theme':
                setBackground()
                break;
            case 'loginout':
                sessionStorage.clear()
                setTimeout(function(){
                    window.location.href="login.html"
                },500)
                break;
            default:
                layer.alert('这个功能还没有实现哟')
                break;
        }
    })
  
  /*******************开始菜单end*******************/
   
   
   
   
        
/****调用方法***/
//打开窗口
function openlayer(){
    var nowlength=$('.layui-tab-title li').length
    var iconHtml=$(this).find('i')[0].outerHTML
    var nameHtml=$(this).find('span')[0].outerHTML
    var title=$(this).find('span').html()
    var reg3=/"color:(.*)"/g
    if(nameHtml.match(reg3)){
        var fontcolor=reg3.exec(nameHtml)[1]
    }
    nameHtml=nameHtml.replace(fontcolor,"#fff")
    var href=$(this).data('url')
    var reg=/(.*)(\.html)/g
    var reg2=/\/(\w*)(\.html)/g
    var hrefid=reg.exec(href)[1]
    var layid=reg2.exec(href)[1]
    var tabone=iconHtml+nameHtml
    
    //本地存储记录
    if($(this)[0]['offsetParent']['className'].indexOf('opening-menu')==-1){
        var thisstring=encodeURIComponent(this.outerHTML)
        var localstorageNavString=localStorage.getItem('localNav')
        var localstorageNav=localstorageNavString ? JSON.parse(localstorageNavString):{"total":"0"}
        if(localstorageNav.hasOwnProperty(thisstring)){
           localstorageNav[thisstring]++
        }else{
           localstorageNav[thisstring]=1
           localstorageNav['total']++
        }
        var nowNavString=JSON.stringify(localstorageNav)
        localStorage.setItem('localNav',nowNavString)
    }
    //含有子元素
    if($(this).data('child')){
        var childNav=$(this).data('child')
        var tplData={curData:childNav}
        var html = template('tpl-childList', tplData);
            //console.log(html)
            //$('.desktop-main').html(html);
             //return false;
        if(!tabarr.hasOwnProperty(hrefid)){
            if(nowlength>9){
                layer.msg('最多可以打开10个窗口哟！',{zIndex: layer.zIndex,success:function(layero){                      layer.setTop(layero);}})
                return false
            }
            element.tabAdd('demo', {
              title: tabone,
              id:hrefid
            });
            var index=layer.open({
                type:1,
                id:layid,
                title:title,
                content:html,
                shadeClose:true,
                shade:false,
                maxmin:true,
                zIndex: layer.zIndex,
                area:["50%","50%"],
                end:function(){
                    
//                      return false;
                    element.tabDelete('demo',hrefid);
                    delete tabarr[hrefid];
                    console.log(tabarr)
                },
                success:function(layero){
                    var thistab=$('.layui-tab-title').find('li[lay-id="'+hrefid+'"]')
                    thistab.addClass('layui-this').siblings('li').removeClass('layui-this')
                    layer.setTop(layero);
                },
                min:function(e){
                    var thistab=$('.layui-tab-title').find('li[lay-id="'+hrefid+'"]')
                    thistab.removeClass('layui-this')
                }
            })
            tabarr[hrefid]=index
        }else{
            showtablayer(hrefid,tabarr[hrefid])
//              layer.restore(tabarr[hrefid])
        }
    }else{
        if(!tabarr.hasOwnProperty(hrefid)){
            if(nowlength>9){
                layer.msg('最多可以打开10个窗口哟！',{zIndex: layer.zIndex,success:function(layero){layer.setTop(layero);}})
                return false
            }
            element.tabAdd('demo', {
              title: tabone,
              id:hrefid
            });
            var thisurl=$(this).data('url')
            var index=layer.open({
                type:2,
                id:layid,
                title:title,
                content:thisurl,
                shadeClose:true,
                shade:false,
                maxmin:true,
                area:["50%","50%"],
                zIndex: layer.zIndex,
                end:function(){
//                      return false;
                    element.tabDelete('demo',hrefid);
                    delete tabarr[hrefid];
                    console.log(tabarr)
                },
                success:function(layero){
                    var thistab=$('.layui-tab-title').find('li[lay-id="'+hrefid+'"]')
                    thistab.addClass('layui-this').siblings('li').removeClass('layui-this')
                    layer.setTop(layero);
                },
                min:function(e){
                    var thistab=$('.layui-tab-title').find('li[lay-id="'+hrefid+'"]')
                    thistab.removeClass('layui-this')
                }
            })
            tabarr[hrefid]=index
        }else{
            showtablayer(hrefid,tabarr[hrefid])
        }
        console.log(tabarr)
    }
    $(this).css('background','')
}




//呼出置顶
function showtablayer(tabid,tab){
    var tabId=tabid
    var tabIndex=tab
    var maxindex=0
    $('body').children('.layui-layer').each(function(k,v){
       if(maxindex<layer.setTop($(v))){
           maxindex=layer.setTop($(v))
       }
    })
    maxindex=maxindex+1
    $("#layui-layer"+tabIndex).css('z-index',maxindex)
    var nowZindex=layer.setTop($("#layui-layer"+tabIndex))
    console.log(nowZindex)
    var thistab=$('.layui-tab-title').find('li[lay-id="'+tabId+'"]')
    thistab.addClass('layui-this').siblings('li').removeClass('layui-this')
    try{
        layer.restore(tabIndex)
    }catch(e){
        if(e){
            return
        }else{
             layer.restore(tabIndex)
        }
    }
}
// 判断各种浏览器，找到正确的方法,全屏
function launchFullscreen(element) {
  if(element.requestFullscreen) {
    element.requestFullscreen();
  } else if(element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if(element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();
  } else if(element.msRequestFullscreen) {
    element.msRequestFullscreen();
  }
}
//时间同步
function getNowTime(){
    var nowdate,nowtime,nowall
    function getNow(){
        nowtime=timeDate('','4')
        nowdate=timeDate('','1')
        nowall=timeDate('','5')
        $("#laydate-ymd").html(nowdate)
        $("#laydate-hs").html(nowtime)
        $(".taskbar-time").attr('title',nowall)
    }
    getNow()
    setInterval(function(){getNow()},10000)
}
//背景设置
function setBackground(){
    var oldimgurl=$('.desktop-container').css('background-image')
    var nowimgurl=$('.desktop-container').css('background-image')
    $.ajax({
        type:"get",
        url:"bgimages.json",
        async:true,
        success:function(data){
        var tplData={curData:data}
        var html = template('tpl-bgList', tplData);
            layer.open({
                content: html,
                title:'背景设置',
                area:["640px","50%"],
                btn:['应用'],
                success:function(layero, index){
                    layero.find('.set-themes').on('click',function(){
                        var obj=$(this)
                        var imgurl=obj.data('url')
                        nowimgurl="url("+imgurl+")"
                        $('.desktop-container').css('background-image',nowimgurl)
                    })
                },
                yes: function(index, layero){
                    localStorage.setItem('setbg',nowimgurl)
                    layer.close(index);
                },
                cancel: function(index, layero){ 
                    $('.desktop-container').css('background-image',oldimgurl)
                } 
            });     
        }
    });
}
/****调用方法end***/
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
});